package service.impl;

import bean.Menu;
import dao.MenuDao;
import dao.MiddleDao;
import dao.impl.MenuDaoImpl;
import dao.impl.MiddleDaoImpl;
import service.MenuService;

import java.util.ArrayList;
import java.util.List;

public class MenuServiceImpl implements MenuService {

    private MenuDao dao = new MenuDaoImpl();
    private MiddleDao middleDao = new MiddleDaoImpl();

    @Override
    public List<Menu> getMenuList() {

        //获得最初所有菜单
        List<Menu> beforeMenuList = dao.getMenuList();
        //保存分级后的菜单
        List<Menu> newMenuList = new ArrayList<>();

        for(Menu menu:beforeMenuList) {
            //区分一，二级菜单
            if (menu.getUpMenuId()==0){

                List<Menu> secondMenuList = new ArrayList<>();

                //在UpMenuId=0的前提下循环最初菜单，当second.getUpMenuId()==menu.getMenuId()时找到一二级对应关系
                for(Menu second:beforeMenuList){
                    //二级满足和一级菜单匹配时，存入二级菜单
                    if (second.getUpMenuId()==menu.getMenuId()){
                        secondMenuList.add(second);
                    }
                }
                //将二级菜单数据存入菜单对象中
                menu.setSecondMenuList(secondMenuList);
                //将分好一二级的菜单数据，重新存储到新集合中
                newMenuList.add(menu);
            }

        }

        return newMenuList;
    }

    @Override
    public List<Menu> getRoleMenu(int roleId) {

        List<Integer> menuIds = middleDao.findById(roleId);

        List<Menu> roleMenus = dao.getRoleMenu(menuIds);


        return roleMenus;
    }

    /**
     * 更新角色菜单时：1.根据roleId先删除该角色中间菜单表数据 2.重新插入菜单数据
     * @param roleId roleId
     * @param menuIds 页面获取的新的菜单主键
     * @return 返回受影响行数
     */
    @Override
    public int updateMenu(int roleId ,String[] menuIds) {


        int flag = middleDao.updateMenu(roleId,menuIds);


        return flag;
    }

}
